package com.myapp.api.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.myapp.api.tools.JWTUtils;
import com.myapp.api.tools.JsonResult;
import com.myapp.api.tools.ResultStatus;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof HandlerMethod) {
            String authHeader = request.getHeader(JWTUtils.TOKEN_HEADER);
            if (StringUtils.isEmpty(authHeader)) {
                print(response, ResultStatus.NOT_EXIST_TOKEN);
                return false;
            } else {
                if (!JWTUtils.isExpiration(authHeader)) return true;
                else {
                    print(response, ResultStatus.TOKEN_EXPIRED);
                    return false;
                }
            }
        } else return true;
    }

    public void print(HttpServletResponse response, ResultStatus record) {
        try {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setHeader("Cache-Control", "no-cache, must-revalidate");
            PrintWriter writer = response.getWriter();
            ObjectMapper mapper = new ObjectMapper();
            JsonResult jsonResult = new JsonResult(record);
            writer.write(mapper.writeValueAsString(jsonResult));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
